<template>
  <div class="callback-container">
    <div v-if="loading"
class="loading">
      <span>正在处理微信授权...</span>
    </div>
    <div v-if="error"
class="error">
      {{ error }}
      <button @click="retry">重试</button>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { handleWechatCallback } from '@/services/wechat'

  const route = useRoute()
  const router = useRouter()
  const loading = ref(true)
  const error = ref('')

  onMounted(async () => {
    try {
      const code = route.query.code
      if (!code) {
        throw new Error('缺少授权码参数')
      }

      const result = await handleWechatCallback(code)

      if (result.needBind) {
        router.push({
          name: 'AccountBind',
          query: {
            openid: result.openid,
            nickname: result.nickname,
            avatar: result.avatar,
          },
        })
      } else {
        // 保存登录状态
        localStorage.setItem('token', result.token)
        localStorage.setItem('user', JSON.stringify(result.user))
        router.push('/')
      }
    } catch (err) {
      error.value = err.message || '微信授权处理失败'
    } finally {
      loading.value = false
    }
  })

  const retry = () => {
    window.location.href = '/login'
  }
</script>

<style scoped>
  .callback-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
  }

  .loading {
    font-size: 18px;
  }

  .error {
    color: #f56c6c;
    margin-top: 20px;
  }

  .error button {
    margin-top: 10px;
    padding: 5px 15px;
    background: #07c160;
    color: white;
    border: none;
    border-radius: 4px;
  }
</style>
